import React, { useState, useEffect, useRef, useMemo } from 'react';
import { 
  Card, Row, Col, Typography, Select, DatePicker, 
  Statistic, Table, Button, Space, message, Spin,
  Skeleton,
  Modal
} from 'antd';
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { 
  UserOutlined, CalendarOutlined, 
  DollarOutlined, DownloadOutlined,
  BarChartOutlined, PieChartOutlined
} from '@ant-design/icons';
import TreatmentDetailModal from '../../component/appointment/TreatmentDetailModal';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 生成固定数据的工具函数
const generateMonthlyData = (months = 6) => {
  return Array.from({ length: months }, (_, i) => {
    const month = dayjs().subtract(months - i - 1, 'month').format('YYYY-MM');
    
    const baseValue = (i + 1) * 30;
    const 预约量 = 150 + baseValue;
    const 取消量 = Math.floor(预约量 * (8 + i * 2) / 100);
    const 完成量 = 预约量 - 取消量;
    const 收入 = 完成量 * (250 + i * 15);
    
    return { month, 预约量, 完成量, 取消量, 收入 };
  });
};

// 模拟数据 - 项目分布数据
const serviceDistributionData = [
  { name: '推拿按摩', 数量: 320, 占比: 32, 收入: 57600 },
  { name: '针灸治疗', 数量: 250, 占比: 25, 收入: 67000 },
  { name: '艾灸养生', 数量: 180, 占比: 18, 收入: 40600 },
  { name: '拔罐疗法', 数量: 150, 占比: 15, 收入: 25200 },
  { name: '中药熏蒸', 数量: 100, 占比: 10, 收入: 29800 },
];

// 模拟数据 - 员工工作量数据
const doctorWorkloadData = [
  { 员工: '李员工', 预约量: 280, 完成率: 92, 平均评分: 4.8, 收入: 76500 },
  { 员工: '陈员工', 预约量: 240, 完成率: 95, 平均评分: 4.9, 收入: 68200 },
  { 员工: '赵员工', 预约量: 210, 完成率: 88, 平均评分: 4.7, 收入: 56800 },
  { 员工: '王员工', 预约量: 170, 完成率: 90, 平均评分: 4.6, 收入: 48300 },
];

// 模拟数据 - 周工作量数据
const weeklyWorkloadData = [
  { 星期: '周一', 预约量: 65, 高峰时段: '15:00-17:00' },
  { 星期: '周二', 预约量: 58, 高峰时段: '14:00-16:00' },
  { 星期: '周三', 预约量: 72, 高峰时段: '10:00-12:00' },
  { 星期: '周四', 预约量: 85, 高峰时段: '15:00-17:00' },
  { 星期: '周五', 预约量: 92, 高峰时段: '16:00-18:00' },
  { 星期: '周六', 预约量: 120, 高峰时段: '09:00-11:00' },
  { 星期: '周日', 预约量: 105, 高峰时段: '10:00-12:00' },
];

// 模拟数据 - 客户分析数据
const customerAnalysisData = [
  { 客户类型: '新客户', 数量: 380, 占比: 42, 平均消费: 268 },
  { 客户类型: '老客户', 数量: 520, 占比: 58, 平均消费: 325 },
];

const AppointmentAnalysis = () => {
  // 初始化日期范围为最近6个月
  const getDefaultDateRange = () => {
    const end = dayjs();
    const start = dayjs().subtract(6, 'month');
    return [start, end];
  };
  
  const [isShow, setIsShow] = useState(true);
  const [dateRange, setDateRange] = useState(getDefaultDateRange());
  const [timeRange, setTimeRange] = useState('month');
  const [loading, setLoading] = useState(false);
  const [monthlyData, setMonthlyData] = useState([]);
  const [chartsInitialized, setChartsInitialized] = useState(false);
  const [isTreatmentDetailModal,set_IsTreatmentDetailModal]=useState(false);
  const [TreatmentDetailData,set_TreatmentDetailData]=useState(null);

  // 初始化数据
  useEffect(() => {
    setMonthlyData(generateMonthlyData());
  }, []);

  // 计算总体统计数据
  const summaryData = useMemo(() => {
    if (!monthlyData.length) {
      return {
        totalAppointments: 0,
        completionRate: 0,
        averagePrice: 0,
        totalRevenue: 0,
        monthOnMonthGrowth: 0,
        newCustomers: 0
      };
    }
    
    const totalAppointments = monthlyData.reduce((sum, item) => sum + item.预约量, 0);
    const totalCompleted = monthlyData.reduce((sum, item) => sum + item.完成量, 0);
    const completionRate = totalAppointments > 0 ? Math.round((totalCompleted / totalAppointments) * 100) : 0;
    const totalRevenue = monthlyData.reduce((sum, item) => sum + item.收入, 0);
    const averagePrice = totalCompleted > 0 ? Math.round(totalRevenue / totalCompleted) : 0;
    
    // 计算环比增长
    let monthOnMonthGrowth = 0;
    if (monthlyData.length >= 2) {
      const lastMonth = monthlyData[monthlyData.length - 1].预约量;
      const prevMonth = monthlyData[monthlyData.length - 2].预约量;
      monthOnMonthGrowth = prevMonth > 0 ? ((lastMonth - prevMonth) / prevMonth * 100).toFixed(1) : 0;
    }
    
    return {
      totalAppointments,
      completionRate,
      averagePrice,
      totalRevenue,
      monthOnMonthGrowth,
      newCustomers: 380
    };
  }, [monthlyData]);

  // ECharts实例引用
  const trendChartRef = useRef(null);
  const servicePieRef = useRef(null);
  const doctorBarRef = useRef(null);
  const weeklyBarRef = useRef(null);
  const customerPieRef = useRef(null);

  // 图表容器DOM引用
  const trendChartContainer = useRef(null);
  const servicePieContainer = useRef(null);
  const doctorBarContainer = useRef(null);
  const weeklyBarContainer = useRef(null);
  const customerPieContainer = useRef(null);

  // 初始化图表
  const initCharts = () => {
    if (!monthlyData.length) return;
    
    // 销毁现有图表实例
    if (trendChartRef.current) {
      trendChartRef.current.dispose();
    }
    if (servicePieRef.current) {
      servicePieRef.current.dispose();
    }
    if (doctorBarRef.current) {
      doctorBarRef.current.dispose();
    }
    if (weeklyBarRef.current) {
      weeklyBarRef.current.dispose();
    }
    if (customerPieRef.current) {
      customerPieRef.current.dispose();
    }
    
    // 创建新的图表实例
    if (trendChartContainer.current) {
      trendChartRef.current = echarts.init(trendChartContainer.current);
    }
    if (servicePieContainer.current) {
      servicePieRef.current = echarts.init(servicePieContainer.current);
    }
    if (doctorBarContainer.current) {
      doctorBarRef.current = echarts.init(doctorBarContainer.current);
    }
    if (weeklyBarContainer.current) {
      weeklyBarRef.current = echarts.init(weeklyBarContainer.current);
    }
    if (customerPieContainer.current) {
      customerPieRef.current = echarts.init(customerPieContainer.current);
    }
    
    // 更新所有图表
    updateAllCharts();
    setChartsInitialized(true);
  };

  // 更新所有图表
  const updateAllCharts = () => {
    if (!monthlyData.length) return;
    
    updateTrendChart();
    updateServicePieChart();
    updateDoctorBarChart();
    updateWeeklyBarChart();
    updateCustomerPieChart();
  };

  // 组件挂载时初始化图表
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsShow(false);
      
      // 窗口大小变化时重绘图表
      const handleResize = () => {
        trendChartRef.current?.resize();
        servicePieRef.current?.resize();
        doctorBarRef.current?.resize();
        weeklyBarRef.current?.resize();
        customerPieRef.current?.resize();
      };
      
      window.addEventListener('resize', handleResize);
      
      // 组件卸载时清理
      return () => {
        window.removeEventListener('resize', handleResize);
        // 销毁图表实例，防止内存泄漏
        trendChartRef.current?.dispose();
        servicePieRef.current?.dispose();
        doctorBarRef.current?.dispose();
        weeklyBarRef.current?.dispose();
        customerPieRef.current?.dispose();
      };
    }, 1000);
    
    return () => clearTimeout(timer);
  }, []);

  // 数据加载完成后初始化图表
  useEffect(() => {
    if (monthlyData.length && !isShow && !chartsInitialized) {
      initCharts();
    }
  }, [monthlyData, isShow, chartsInitialized]);

  // 数据变化时更新图表
  useEffect(() => {
    if (chartsInitialized) {
      updateAllCharts();
    }
  }, [monthlyData, chartsInitialized]);

  // 更新趋势图表数据
  const updateTrendChart = () => {
    if (!trendChartRef.current || !monthlyData.length) return;
    
    const monthLabels = monthlyData.map(item => {
      const month = dayjs(item.month);
      return `${month.month() + 1}月`;
    });
    
    const option = {
      title: {
        text: '预约趋势分析',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: function(params) {
          let res = params[0].name + '<br/>';
          params.forEach(item => {
            res += item.seriesName + ': ' + item.value + '<br/>';
          });
          return res;
        }
      },
      legend: {
        data: ['预约量', '完成量', '取消量'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: monthLabels
      },
      yAxis: { type: 'value', name: '数量' },
      series: [
        {
          name: '预约量',
          type: 'line',
          data: monthlyData.map(item => item.预约量),
          smooth: true,
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: { color: '#8B5A2B' }
        },
        {
          name: '完成量',
          type: 'line',
          data: monthlyData.map(item => item.完成量),
          smooth: true,
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: { color: '#52c41a' }
        },
        {
          name: '取消量',
          type: 'line',
          data: monthlyData.map(item => item.取消量),
          smooth: true,
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: { color: '#CD5C5C' }
        }
      ]
    };

    trendChartRef.current.setOption(option);
  };

  // 更新项目分布饼图
  const updateServicePieChart = () => {
    if (!servicePieRef.current) return;
    
    const colors = ['#8B5A2B', '#2F4F4F', '#52c41a', '#CD5C5C', '#faad14'];
    
    const option = {
      title: {
        text: '理疗项目分布',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: serviceDistributionData.map(item => item.name)
      },
      series: [
        {
          name: '项目数量',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: { show: false, position: 'center' },
          emphasis: {
            label: { show: true, fontSize: 16, fontWeight: 'bold' }
          },
          labelLine: { show: false },
          data: serviceDistributionData.map(item => ({
            name: item.name,
            value: item.数量
          })),
          itemStyle: {
            color: function(params) {
              return colors[params.dataIndex % colors.length];
            }
          },
          animationDuration: 1000,
          animationEasingUpdate: 'quinticInOut'
        }
      ]
    };

    servicePieRef.current.setOption(option);
  };

  // 更新员工工作量柱状图
  const updateDoctorBarChart = () => {
    if (!doctorBarRef.current) return;
    
    const option = {
      title: {
        text: '员工工作量分析',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: ['预约量', '完成率(%)'], top: 30 },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: doctorWorkloadData.map(item => item.员工)
      },
      yAxis: [
        { type: 'value', name: '预约量' },
        { type: 'value', name: '完成率(%)', max: 100 }
      ],
      series: [
        {
          name: '预约量',
          type: 'bar',
          data: doctorWorkloadData.map(item => item.预约量),
          barWidth: '40%',
          itemStyle: { color: '#8B5A2B' }
        },
        {
          name: '完成率(%)',
          type: 'line',
          yAxisIndex: 1,
          data: doctorWorkloadData.map(item => item.完成率),
          lineStyle: { width: 3, color: '#CD5C5C' },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: { color: '#CD5C5C' }
        }
      ]
    };

    doctorBarRef.current.setOption(option);
  };

  // 更新周工作量柱状图
  const updateWeeklyBarChart = () => {
    if (!weeklyBarRef.current) return;
    
    const option = {
      title: {
        text: '周工作量分布',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: function(params) {
          const index = params[0].dataIndex;
          return `${params[0].name}<br/>预约量: ${params[0].value}<br/>高峰时段: ${weeklyWorkloadData[index].高峰时段}`;
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: weeklyWorkloadData.map(item => item.星期)
      },
      yAxis: { type: 'value', name: '预约量' },
      series: [
        {
          name: '预约量',
          type: 'bar',
          data: weeklyWorkloadData.map(item => item.预约量),
          itemStyle: {
            color: function(params) {
              // 周末使用不同颜色
              if (params.dataIndex === 5 || params.dataIndex === 6) {
                return '#CD5C5C';
              }
              return '#8B5A2B';
            }
          },
          barWidth: '60%',
          animationDuration: 1000
        }
      ]
    };

    weeklyBarRef.current.setOption(option);
  };

  // 更新客户类型饼图
  const updateCustomerPieChart = () => {
    if (!customerPieRef.current) return;
    
    const option = {
      title: {
        text: '客户类型分布',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)<br/>平均消费: ¥{e}'
      },
      series: [
        {
          name: '客户数量',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: { show: false, position: 'center' },
          emphasis: {
            label: { show: true, fontSize: 16, fontWeight: 'bold' }
          },
          labelLine: { show: false },
          data: customerAnalysisData.map(item => ({
            name: item.客户类型,
            value: item.数量,
            e: item.平均消费
          })),
          itemStyle: {
            color: function(params) {
              return params.dataIndex === 0 ? '#52c41a' : '#8B5A2B';
            }
          },
          animationDuration: 1000,
          animationEasingUpdate: 'quinticInOut'
        }
      ]
    };

    customerPieRef.current.setOption(option);
  };

  // 刷新图表数据的函数
  const refreshCharts = () => {
    setLoading(true);
    // 使用setTimeout模拟数据加载
    setTimeout(() => {
      const monthsCount = dateRange[1].diff(dateRange[0], 'month') + 1;
      const newData = generateMonthlyData(monthsCount);
      setMonthlyData(newData);
      setLoading(false);
      
      // 数据更新后重新初始化图表
      setChartsInitialized(false);
      setTimeout(() => {
        initCharts();
      }, 100);
    }, 800);
  };

  // 导出数据
  const exportData = () => {
    const startDate = dateRange[0].format('YYYYMMDD');
    const endDate = dateRange[1].format('YYYYMMDD');
    message.success(`数据导出成功: 预约数据分析_${startDate}_${endDate}.xlsx`);
  };

  // 表格列定义 - 员工工作量
  const doctorColumns = [
    { title: '员工', dataIndex: '员工', key: '员工' },
    { title: '预约量', dataIndex: '预约量', key: '预约量' },
    {
      title: '完成率',
      dataIndex: '完成率',
      key: '完成率',
      render: (rate) => (
        <div>
          <span>{rate}%</span>
          <div style={{ marginTop: 4, height: 6, backgroundColor: '#f0f0f0', borderRadius: 3, overflow: 'hidden' }}>
            <div 
              style={{ 
                height: '100%', 
                width: `${rate}%`, 
                backgroundColor: rate > 90 ? '#52c41a' : '#8B5A2B' 
              }}
            ></div>
          </div>
        </div>
      )
    },
    {
      title: '平均评分',
      dataIndex: '平均评分',
      key: '平均评分',
      render: (score) => (
        <div>
          {[...Array(5)].map((_, i) => (
            <span key={i} style={{ color: i < Math.floor(score) ? '#faad14' : '#ccc' }}>★</span>
          ))}
          <span style={{ marginLeft: 5 }}>{score}</span>
        </div>
      )
    },
    { 
      title: '创收(¥)', 
      dataIndex: '收入', 
      key: '收入',
      render: (value) => `¥ ${value.toLocaleString()}`
    },
  ];

  // 表格列定义 - 项目分析
  const serviceColumns = [
    { title: '理疗项目', dataIndex: 'name', key: 'name' },
    { title: '预约数量', dataIndex: '数量', key: '数量' },
    {
      title: '占比',
      dataIndex: '占比',
      key: '占比',
      render: (percent) => (
        <div>
          <span>{percent}%</span>
          <div style={{ marginTop: 4, height: 6, backgroundColor: '#f0f0f0', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${percent}%`, backgroundColor: '#2F4F4F' }}></div>
          </div>
        </div>
      )
    },
    { 
      title: '创收(¥)', 
      dataIndex: '收入', 
      key: '收入',
      render: (value) => `¥ ${value.toLocaleString()}`
    },
    {
      title: '操作',
      key: 'action',
      render: (_,record) => <Button type="primary" onClick={()=>{
        set_IsTreatmentDetailModal(true);
        set_TreatmentDetailData(record);

      }}  size="small">详情</Button>
    },
  ];

  return (
    <div>
      {isShow ? (
        <Skeleton paragraph={{ rows: 10 }} active />
      ) : (
        <div>
          {/* 页面标题和操作区 */}
          <div style={{ marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap' }}>
            <div>
              <Title level={2} style={{ marginBottom: 5 }}>预约数据分析</Title>
              <Text type="secondary">全面分析预约数据，掌握业务运营情况</Text>
            </div>
            <Space size="middle" style={{ marginTop: 10 }}>
              <RangePicker 
                value={dateRange}
                onChange={setDateRange}
                style={{ width: 300 }}
                placeholder={['开始日期', '结束日期']}
              />
              <Select 
                value={timeRange} 
                onChange={setTimeRange}
                style={{ width: 120 }}
                placeholder="选择时间范围"
              >
                <Option value="week">按周</Option>
                <Option value="month">按月</Option>
                <Option value="quarter">按季度</Option>
              </Select>
              <Button 
                icon={<CalendarOutlined />} 
                onClick={refreshCharts}
                loading={loading}
              >
                刷新数据
              </Button>
              <Button 
                icon={<DownloadOutlined />}
                onClick={exportData}
              >
                导出报表
              </Button>
            </Space>
          </div>
          
          {/* 核心指标卡片 */}
          <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="总预约量"
                  value={summaryData.totalAppointments}
                  prefix={<CalendarOutlined />}
                 
                />
              </Card>
            </Col>
            
            <Col xs={24} sm={12} lg={4}>
              <Card hoverable>
                <Statistic
                  title="完成率"
                  value={summaryData.completionRate}
                  valueStyle={{ color: summaryData.completionRate > 90 ? '#52c41a' : '#8B5A2B' }}
                  prefix={<PieChartOutlined />}
                  suffix="%"
                />
              </Card>
            </Col>
           
            <Col xs={24} sm={12} lg={4}>
              <Card hoverable>
                <Statistic
                  title="平均客单价"
                  value={summaryData.averagePrice}
                  prefix={<DollarOutlined />}
                  valueStyle={{ color: '#8B5A2B' }}
                  formatter={value => `¥ ${value}`}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card hoverable>
                <Statistic
                  title="总创收"
                  value={summaryData.totalRevenue}
                  prefix={<DollarOutlined />}
                  valueStyle={{ color: '#CD5C5C' }}
                  formatter={value => `¥ ${value.toLocaleString()}`}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card hoverable>
                <Statistic
                  title="环比增长"
                  value={summaryData.monthOnMonthGrowth}
                  valueStyle={{ color: summaryData.monthOnMonthGrowth > 0 ? '#52c41a' : '#f5222d' }}
                  prefix={<BarChartOutlined />}
                  suffix="%"
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card hoverable>
                <Statistic
                  title="新增客户"
                  value={summaryData.newCustomers}
                  prefix={<UserOutlined />}
                  valueStyle={{ color: '#2F4F4F' }}
                />
              </Card>
            </Col>
          </Row>
          
          {/* 图表区域 */}
          <Spin spinning={loading} tip="加载数据中...">
            <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
              <Col xs={24} lg={16}>
                <Card>
                  <div 
                    ref={trendChartContainer} 
                    style={{ width: '100%', height: 400 }}
                  ></div>
                </Card>
              </Col>
              <Col xs={24} lg={8}>
                <Card>
                  <div 
                    ref={servicePieContainer} 
                    style={{ width: '100%', height: 400 }}
                  ></div>
                </Card>
              </Col>
            </Row>
            
            <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
              <Col xs={24} lg={12}>
                <Card>
                  <div 
                    ref={doctorBarContainer} 
                    style={{ width: '100%', height: 400 }}
                  ></div>
                </Card>
              </Col>
              <Col xs={24} lg={12}>
                <Card>
                  <div 
                    ref={weeklyBarContainer} 
                    style={{ width: '100%', height: 400 }}
                  ></div>
                </Card>
              </Col>
            </Row>
            
            <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
              <Col xs={24} lg={8}>
                <Card>
                  <div 
                    ref={customerPieContainer} 
                    style={{ width: '100%', height: 350 }}
                  ></div>
                </Card>
              </Col>
              <Col xs={24} lg={16}>
                <Card title="员工工作量详情">
                  <Table 
                    columns={doctorColumns} 
                    dataSource={doctorWorkloadData} 
                    pagination={false}
                    rowKey="员工"
                    scroll={{ x: 'max-content' }}
                  />
                </Card>
              </Col>
            </Row>
            
            <Row gutter={[16, 16]}>
              <Col xs={24}>
                <Card title="理疗项目分析详情">
                  <Table 
                    columns={serviceColumns} 
                    dataSource={serviceDistributionData} 
                    pagination={{ pageSize: 5 }}
                    rowKey="name"
                    scroll={{ x: 'max-content' }}
                  />
                </Card>
              </Col>
            </Row>
          </Spin>


           <Modal
                title={`详情`}
                open={isTreatmentDetailModal}
                onCancel={()=>set_IsTreatmentDetailModal(false)}
                width={900}
                footer={null}
                destroyOnHidden
               
                
              >
                <TreatmentDetailModal data={TreatmentDetailData}></TreatmentDetailModal>
              </Modal>
        </div>
      )}
    </div>
  );
};

export default AppointmentAnalysis;